package com.chunfeng.lerunapplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.chunfeng.lerunapplication.api.UserApi;
import com.chunfeng.lerunapplication.entity.JsonRequest;
import com.chunfeng.lerunapplication.utils.CacheUtils;

/**
 * 窗体类
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    /**
     * 用户名
     */
    private EditText username;
    /**
     * 用户名校验
     */
    private TextView usernameMassage;
    /**
     * 密码
     */
    private EditText password;
    /**
     * 密码校验
     */
    private TextView passwordMessage;

    /**
     * 导入用户API
     */
    private UserApi userApi = new UserApi(this);
    /**
     * 缓存
     */
    private CacheUtils cacheUtils;

    /**
     * 初始化组件
     *
     * @param savedInstanceState 组件资源
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
    }

    /**
     * 初始化组件
     */
    private void init() {
        username = findViewById(R.id.Register_UserName);
        password = findViewById(R.id.Password);
        usernameMassage = findViewById(R.id.Login_Name_Message);
        passwordMessage = findViewById(R.id.login_Password_Message);
        cacheUtils = new CacheUtils(this);
    }

    /**
     * 按钮点击事件
     *
     * @param v 点击的按钮
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.Login) {
            login();
        } else if (id == R.id.Register) {
            Intent register = new Intent(this, RegisterActivity.class);
            startActivity(register);
        }
    }

    /**
     * 登录逻辑
     */
    private void login() {
        String username = this.username.getText().toString();
        String password = this.password.getText().toString();
        usernameMassage.setVisibility(username.isEmpty() ? View.VISIBLE : View.INVISIBLE);
        passwordMessage.setVisibility(password.isEmpty() ? View.VISIBLE : View.INVISIBLE);
        if (username.isEmpty() || password.isEmpty()) {
            return;
        }
        JsonRequest<String> request = userApi.login(username, password);
        if (request != null && request.getSuccess()) {
            Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
            Intent page = new Intent(this, PageActivity.class);
            startActivity(page);
        } else {
            cacheUtils.clear();
            Toast.makeText(this, "登录失败!", Toast.LENGTH_SHORT).show();
        }
    }
}